package cn.wolfcode.service.impl;

import cn.wolfcode.domain.Employee;
import cn.wolfcode.domain.Notice;
import cn.wolfcode.mapper.EmployeeMapper;
import cn.wolfcode.mapper.NoticeMapper;
import cn.wolfcode.qo.NoticeQueryObject;
import cn.wolfcode.service.INoticeService;
import cn.wolfcode.util.UserContext;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Service
public class NoticeServiceImpl implements INoticeService {
    @Autowired
    private NoticeMapper noticeMapper;
    @Autowired
    private EmployeeMapper employeeMapper;

    @Override
    @Transactional
    public void delete(Long id) {
        noticeMapper.deleteByPrimaryKey(id);
    }

    @Override
    @Transactional
    public Long insert(Notice notice) {
        notice.setCreator(UserContext.getEmployee());
        notice.setCreateTime(new Date());
        notice.setHaveRead(Notice.UNREAD);
        notice.setIssueStatus(Notice.UNPUBLISHED);
        noticeMapper.insert(notice);
        return notice.getId();
    }

    @Override
    public Notice get(Long id) {
        return noticeMapper.selectByPrimaryKey(id);
    }

    @Override
    public List<Notice> listAll() {
        return noticeMapper.selectAll();
    }

    @Override
    @Transactional
    public void update(Notice notice) {
        noticeMapper.updateByPrimaryKey(notice);
    }

    @Override
    public PageInfo<Notice> query(NoticeQueryObject qo) {
        // 使用分页插件，传入当前页，每页显示数量
        PageHelper.startPage(qo.getCurrentPage(), qo.getPageSize(),"n.create_time desc");
        // 返回查询一页展示的数据
        if (UserContext.getEmployee().isAdmin()) {
            return new PageInfo<>(noticeMapper.selectForList(qo));
        } else {
            return new PageInfo<>(noticeMapper.selectByIssue(qo));
        }
    }

    // 更新 已读状态
    @Override
    public void updateRead(Long nId,Long eId) {
        noticeMapper.updateRead(nId,eId);
    }

    // 发布
    @Override
    public void updateIssue(Long id) {
        if (id != null) {
            noticeMapper.updateIssue(id);
        }
    }

    // 往中间表插入关系
    @Override
    public void insertRelation(Long id) {
        // 给所有员工发布公告
        List<Employee> employees = employeeMapper.selectAll();
        for (Employee employee : employees) {
            noticeMapper.insertRelation(employee.getId(), id,0);
        }
    }

    // 取消
    @Override
    public void updateRemove(Long id) {
        if (id != null) {
            noticeMapper.updateRemove(id);
        }
    }
}
